package br.megareleased.tvshow;

import java.util.HashSet;
import java.util.Set;

import org.appwork.utils.event.Eventsender;

import br.megareleased.gui.TrayController;
import br.megareleased.model.Episode;
import br.megareleased.model.Series;


class FollowControllerBroadcaster extends Eventsender<FollowControllerListener, FollowControllerEvent> {

    @Override
    protected void fireEvent(final FollowControllerListener listener, final FollowControllerEvent event) {
        listener.onFollowControllerEvent(event);
    }
}

public class FollowController implements FollowControllerListener, FollowControllerInterface {

    private transient FollowControllerBroadcaster broadcaster = new FollowControllerBroadcaster();
	private Set<Series> followList = new HashSet<Series>();
    private static FollowController INSTANCE = new FollowController();

    public static FollowController getInstance() {
        return INSTANCE;
    }

    private FollowController() {
        broadcaster.addListener(this);
        
        SerieController.getInstance().addListener(new SerieControllerListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onSerieControllerEvent(SerieControllerEvent event) {
				if(event.getEventID() == SerieControllerEvent.ADD_EPISODE)
					processFollow();
			}
		});
    }

    public void addListener(final FollowControllerListener l) {
        broadcaster.addListener(l);
    }

    public void removeListener(final FollowControllerListener l) {
        broadcaster.removeListener(l);
    }

	@Override
	public void addToFollow(Series... sl) {
		for (Series serie : sl) {
			if(this.followList.add(serie)) {
				broadcaster.fireEvent(new FollowControllerEvent(this, FollowControllerEvent.ADD_SERIE, serie));
			}
		}
		processFollow();
	}

	@Override
	public void removeFromFollow(Series... sl) {
	}
	
	private void processFollow() {
		Set<Episode> episodeList = SerieController.getInstance().getEpisodeList();
		for (Episode episode : episodeList) {
			if(followList.contains(episode.getSerie())) {
				TrayController.getInstance().showMessage(episode.getSerie().getSeriesName() +" S"+ episode.getSeasonNumber() +"E"+ episode.getEpisodeNumber() +": "+ episode.getEpisodeName(), episode.getOverview());
				System.out.println("download");
				//TODO INICIAR DOWNLOAD
			}
		}
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onFollowControllerEvent(FollowControllerEvent event) {
	    switch (event.getEventID()) {
        case FollowControllerEvent.ADD_SERIE:
        case FollowControllerEvent.REMOVE_SERIE:
        case FollowControllerEvent.REFRESH_DATA:
        }
	}
}
